import Taro from "@tarojs/taro";
import Qs from 'qs'
import getSign from "./sign"

// api请求封装
const serve = function (content) {
  let { url, data, method, showToast } = content
  let timeStramp = Math.round(new Date().getTime() / 1000).toString();
  let sign = getSign(timeStramp)
  data = { ...data, timeStramp, sign }
  data = Qs.stringify(data);
  let header = {
    'content-type': 'application/x-www-form-urlencoded'
  }

  if (showToast) {
    Taro.showLoading({
      title: '加载中',
    })
  }

  return new Promise((resolve, reject) => {
    Taro.request({
      url: HOST + url,
      mode: 'cors',
      data: data,
      method: method,
      header: header
    }).then((res) => {
      Taro.hideLoading()
      if (res.data.code !== 200) {
        Taro.showToast({
          title: res.data.msg,
          icon: 'none',
        })
        setTimeout(() => {
          Taro.redirectTo({
            url: "/pages/index/index"
          })
        }, 500);
      } else {
        return resolve(res.data)
      }
    }).catch(err => {
      console.log(err)
      Taro.showToast({
        title: '数据请求失败',
        icon: 'none'
      })
      setTimeout(() => {
        Taro.redirectTo({
          url: "/pages/index/index"
        })
      }, 500);
      return reject(err)
    })
  })
}

export default serve